#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
typedef struct TreeNode {
	int data;
	struct TreeNode* left;
	struct TreeNode* right;

}TreeNode;
TreeNode* creatNode(int data)
{
	TreeNode* newNode = (TreeNode*)malloc(sizeof(TreeNode));
	if (newNode == NULL)
	{
		exit(1);
	}
	newNode->data = data;
	newNode->left = NULL;
	newNode->right = NULL;
	return newNode;
}
TreeNode* buildTree(int* values, int n)
{
	if (n <= 0)
	{
		return NULL;
	}
	TreeNode** nodes = (TreeNode**)malloc(sizeof(TreeNode**) * n);
	for (int i = 0; i < n; i++)
	{
		if (values[i] == 0)
		{
			nodes[i] = NULL;
		}
		else
		{
			nodes[i] = creatNode(values[i]);
		}
	}
	int parentIndex = 0;
	for (int i = 0; i < n; i++)
	{
		if (nodes[i] != NULL)
		{
			int leftIndex = 2 * i + 1;
			int rightIndex = 2 * i + 2;
			if (leftIndex < n)
			{
				nodes[i]->left = nodes[leftIndex];
			}
			if (rightIndex < n)
			{
				nodes[i]->right = nodes[rightIndex];
			}
			parentIndex++;
		}
	}
	TreeNode* root = nodes[0];
	free(nodes);
	return root;
}
int getDepth(TreeNode* root)
{
	if (root == NULL)
	{
		return 0;
	}
	int leftDepth = getDepth(root->left);
	int rightDepth = getDepth(root->right);
	return (leftDepth > rightDepth) ? (leftDepth + 1) : (rightDepth + 1);

}
void inorder(TreeNode* root)
{
	if (root == NULL)
	{
		return;
	}
	inorder(root->left);
	printf(" %d", root->data);
	inorder(root->right);
}
int main()
{
	int n;
	scanf("%d", &n);
	while (n--)
	{
		int value;
		int values[100];
		int count = 0;
		while (scanf("%d", &value) == 1 && value != -1)
		{
			values[count++] = value;
		}
		TreeNode* root = buildTree(values, count);
		int depth = getDepth(root);
		printf("%d", depth);
		inorder(root);
		printf("\n");
	}
}